﻿using BUGCOME.Infrastructure;
using BUGCOME.Infrastructure.Attribute;
using BUGCOME.Model.Auth;
using BUGCOME.ServiceCore.Services.IServices;

namespace BUGCOME.ServiceCore.Services
{
    /// <summary>
    /// 角色权限
    /// </summary>
    [AppService(ServiceType = typeof(IPermissionService), ServiceLifetime = LifeTime.Transient)]
    public class PermissionService : IPermissionService
    {
        private readonly IRoleService roleService;
        private readonly IMenuService menuService;

        public PermissionService(
            IRoleService RoleService,
            IMenuService MenuService)
        {
            this.roleService = RoleService;
            this.menuService = MenuService;
        }

        /// <summary>
        /// 获取角色数据权限
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>角色权限信息</returns>
        public async Task<List<string>> GetRolePermissionAsync(UserBase user)
        {
            List<string> roles = new();
            // 管理员拥有所有权限
            if (user.IsAdmin)
            {
                roles.Add("admin");
            }
            else
            {
                roles.AddRange(await roleService.SelectUserRoleKeysAsync(user.Id));
            }
            return roles;
        }

        /// <summary>
        /// 获取菜单数据权限
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>菜单权限信息</returns>
        public async Task<List<string>> GetMenuPermissionAsync(UserBase user)
        {
            List<string> perms = new();
            // 管理员拥有所有权限
            if (user.IsAdmin || (await GetRolePermissionAsync(user)).Exists(f => f.Equals(GlobalConstant.AdminRole)))
            {
                perms.Add(GlobalConstant.AdminPerm);
            }
            else
            {
                perms.AddRange(await menuService.SelectMenuPermsByUserIdAsync(user.Id));
            }
            return perms;
        }
    }
}
